﻿using System;
using ZFine.Application.Gas;
using ZFine.Application.SystemManage;
using ZFine.Code;
using ZFine.Domain.Entity.Gas;
using ZFine.Domain.Entity.SystemManage;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;

namespace ZFine.Web.Areas.Gas.Controllers
{
    public class ClassController : ControllerBase
    {
        private SchoolApp schoolApp = new SchoolApp();
        private ClassApp classApp = new ClassApp();
        private RollOutRecordApp rollOutRecordApp = new RollOutRecordApp();

        [HttpGet]
        [HandlerAuthorize(ignore: false)]
        public override ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(ignore: false)]
        public override ActionResult Form()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public override ActionResult Details()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult Update()
        {
            return View();
        }
        [HandlerAuthorize(ignore: false)]
        public ActionResult Upload()
        {
            return View();
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJson(Pagination pagination, SchoolEntity in_school, string SchoolType)
        {
            List<SchoolEntity> l_school = schoolApp.GetIQueryable(SchoolType).ToList();
            List <ClassEntity> l_class = classApp.GetIQueryable("","").ToList();

            var rows = from _school in l_school
                       join _class in l_class on _school.F_Id equals _class.SchoolId into merge
                       from m in merge
                       select new
                       {
                           SchoolId = _school.F_Id,
                           ClassId = m?.F_Id?? "",
                           SchoolName = _school.SchoolName,
                           SchoolType = _school.SchoolType,
                           Class = m?.Class ?? "",
                           ClassFreeTotalAmount = m?.ClassFreeTotalAmount ?? "",
                           ClassFreeAmount = m?.ClassFreeAmount ?? "",
                           Content = m?.Content ?? "",
                           SortId = m?.SortId ?? "",
                           isEnable = m?.isEnable ?? false,
                       };

            //记录总数
            pagination.records = rows.ToArray().Length;
            //总页数
            int pageMod = pagination.records % pagination.rows;
            int pageTotal = pagination.records / pagination.rows;
            if (0 != pageMod) pageTotal = pageTotal + 1;
            //当前页的数据
            rows = rows.Skip((pagination.page - 1) * pagination.rows).Take(pagination.rows).ToList();
            var data = new
            {
                page = pagination.page,//当前页  1  2 3 之类
                records = pagination.records,//总条数  这里应该是18
                rows = rows,//分页的数据
                total = pagination.total,//页数
            };
            return Content(data.ToJson());
        }
        //修改页数据
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJsonForUpdate(string keyValue)
        {
            ClassEntity data = classApp.GetForm(keyValue);
            return Content(data.ToJson());
        }
        //取得最大的排序号
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetMaxSortId()
        {
            int maxSortId = classApp.GetMaxSortId() + 1;
            return Content(maxSortId.ToJson());
        }
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitForm(ClassEntity classEntity, string keyValue)
        {
            if (string.IsNullOrEmpty(keyValue))
            {
                string schoolId = classEntity.SchoolId;
                string classValue = classEntity.Class;
                int existCount = classApp.GetCount(schoolId, classValue);
                if (0 < existCount)
                {
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data.Add("message", "当前学校的当前年级已经存在");
                    return Content(data.ToJson());
                }
            }
            classApp.SubmitForm(classEntity, keyValue);
            return Success("操作成功。");
        }
        [HttpPost]
        [HandlerAjaxOnly]
        [HandlerAuthorize(ignore: false)]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteForm(string keyValue)
        {
            classApp.Del(keyValue);
            return Success("删除成功。");
        }
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult GenerateForm()
        {
            List<RollOutRecordEntity> l_rollOutRecord = rollOutRecordApp.GetIQueryable("","","").ToList();
            l_rollOutRecord = l_rollOutRecord.Where(t => t.status == "3").ToList();
            var l_new_rollOutRecord = (from _rollOutRecord in l_rollOutRecord
                                group _rollOutRecord by new
                                {
                                    schoolId = _rollOutRecord.SchoolId,
                                    classValue = _rollOutRecord.Class
                                }
                                into s
                                select new
                                {
                                    schoolId = s.Select(p => p.SchoolId).First(),
                                    classValue = s.Select(p => p.Class).First(),
                                    ClassFreeTotalAmount = s.Count(),
                                }).ToList();

            //先重置当前学校的学位数据
            var schoolIdList = l_new_rollOutRecord.Select(p => p.schoolId).Distinct().ToList();
            for (int i = 0; i < schoolIdList.Count; i++)
            {
                List<ClassEntity> l_class = classApp.GetIQueryable(schoolIdList[i], "").ToList();
                foreach (var item in l_class)
                {
                    item.ClassFreeTotalAmount = "0";
                    classApp.SubmitForm(item, item.F_Id);
                }
            }

            for (int i=0; i< l_new_rollOutRecord.Count; i++)
            {
                string schoolId = l_new_rollOutRecord[i].schoolId;
                string classValue = l_new_rollOutRecord[i].classValue;
                string classFreeTotalAmount = l_new_rollOutRecord[i].ClassFreeTotalAmount.ToString();
                ClassEntity classEntity = classApp.GetEntity(schoolId, classValue);
                if(null != classEntity)
                {
                    //更新
                    classEntity.ClassFreeTotalAmount = classFreeTotalAmount;
                    classApp.SubmitForm(classEntity, classEntity.F_Id);
                }
                else
                {
                    //追加
                    ClassEntity insertClassEntity = new ClassEntity();
                    insertClassEntity.SchoolId = schoolId;
                    insertClassEntity.Class = classValue;
                    insertClassEntity.ClassFreeTotalAmount = classFreeTotalAmount;
                    classApp.SubmitForm(insertClassEntity, "");
                }
            }
            return Success("学位生成成功。");
        }
    }
}
